package com.zhl.service_.impl;

import com.zhl.dao_.ArticleMapper;
import com.zhl.dao_.MessageMapper;
import com.zhl.entity.Article;
import com.zhl.entity.Message;
import com.zhl.service_.ArticleService;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * Created by Administrator on 2018/11/2.
 */
@Service
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private MessageMapper messageMapper;

    @Override
    public int addArticle(Article article) {
        return articleMapper.addArticle(article);
    }

    @Override
    public List<Article> articleList(int pageNumber, int pageSize, String articleType, String title) {


        /*Example example = new Example(Article.class);
        example.createCriteria().andEqualTo("articleType");
        example.orderBy("createTime").orderBy("id").desc();
        List<Article> articleList = articleMapper.selectByExampleAndRowBounds(example, new RowBounds(pageNumber, pageSize));*/

        int start = pageNumber * pageSize;
        List<Article> articleList = articleMapper.articleList(start, pageSize, articleType, title);
        return articleList;
    }

    @Override
    public Article queryArticleById(int id) {
        Example example = new Example(Article.class);
        example.createCriteria().andEqualTo("id",id);
        Article article = articleMapper.selectOneByExample(example);
//        Article article = articleMapper.queryArticleById(id);
        return article;
    }

    @Override
    public int updateArticle(Article article) {
        return articleMapper.updateArticle(article);
    }

    @Override
    public int deleteArticle(int id) {
        //删除文章,文章下的留言也要删除
        List<Message> messageList = messageMapper.commentList(id);

        for (Message message:messageList) {
            //删除留言下的回复
            if (message.getHaschild() == 1) {
                messageMapper.deleteMessageByWriteBack(message.getId());
            }
            //删除属于该文章的留言
            messageMapper.deleteMessageByArticleId(id);
        }
        return articleMapper.deleteArticle(id);
    }

    @Override
    public int getCount() {
        return articleMapper.getCount();
    }
}
